﻿using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace WPFStyleAndBehavior
{
    public class CustomCanvasBehavior : Behavior<UIElement>
    {
        Canvas Canvas;

        bool bDrag = false;

        Point ptStart;

        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.AddHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(MouseLeftButtonDownHandler), true);
            this.AssociatedObject.AddHandler(UIElement.MouseMoveEvent, new MouseEventHandler(MouseMoveHandler), true);
            this.AssociatedObject.AddHandler(UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(MouseLeftButtonUpHandler), true);
        }

        private void MouseLeftButtonUpHandler(object sender, MouseButtonEventArgs e)
        {
            if (bDrag)
            {
                bDrag = false;
                this.AssociatedObject.ReleaseMouseCapture();
            }
        }

        private void MouseMoveHandler(object sender, MouseEventArgs e)
        {
            if (bDrag)
            {
                Point point = e.GetPosition(Canvas);

                this.AssociatedObject.SetValue(Canvas.LeftProperty, point.X - ptStart.X);
                this.AssociatedObject.SetValue(Canvas.TopProperty, point.Y - ptStart.Y);

            }
        }

        private void MouseLeftButtonDownHandler(object sender, MouseButtonEventArgs e)
        {
            if (Canvas == null)
            {
                Canvas = VisualTreeHelper.GetParent(this.AssociatedObject) as Canvas;
            }
            ptStart = e.GetPosition(this.AssociatedObject);
            bDrag = true;
            this.AssociatedObject.CaptureMouse();

        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.RemoveHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(MouseLeftButtonDownHandler));
            this.AssociatedObject.RemoveHandler(UIElement.MouseMoveEvent, new MouseEventHandler(MouseMoveHandler));
            this.AssociatedObject.RemoveHandler(UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(MouseLeftButtonUpHandler));
        }
    }
}
